﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace SBPweb.Forge.Communication.WCF
{

    public class PollingDuplexServerService<TClientService> : IPollingDuplexServerService
        where TClientService : PollingDuplexClientService
    {

        #region Private fields

        private TClientService client;

        #endregion

        #region Property accessors

        public TClientService Client
        {
            get
            {
                return client;
            }
        }

        public string SessionId
        {
            get;
            private set;
        }

        #endregion

        #region Methods

        public virtual void Register(Message message)
        {
            string body = message.GetBody<string>();
            string token = "SessionId=";
            if (body.Contains(token))
            {
                foreach(string spl in body.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if(spl.StartsWith(token))
                    {
                        SessionId = spl.Substring(token.Length);
                    }
                }
            }
            client = (TClientService)Activator.CreateInstance(
                                                typeof(TClientService),
                                                OperationContext.Current.GetCallbackChannel<IPollingDuplexClientService>(),
                                                "forge.SBPweb.hu/IPollingDuplexServerService/Send",
                                                SessionId);

            client.Faulted += new EventHandler<PollingDuplexClientService.FaultedEventArgs>(client_Faulted);
        }

        private void client_Faulted(object sender, PollingDuplexClientService.FaultedEventArgs e)
        {
            client = null;
        }

        public virtual void Sync(Message message)
        {
            throw new NotImplementedException();
        }

        #endregion

    }

}